import type { FC } from 'react';
import React, { useState } from 'react';
import { LikeOutlined, MessageOutlined, StarOutlined } from '@ant-design/icons';
import { ModalForm, ProFormDigit, QueryFilter, ProFormSelect, ProFormText, ProFormDependency } from '@ant-design/pro-form';
import { Avatar, Card, Input, List, Radio, Space, message, Button } from 'antd';
import { useEffect } from 'react';
import { history } from 'umi';

import { PageContainer } from '@ant-design/pro-layout';
import type { RadioChangeEvent } from 'antd';
import moment from 'moment';
import { queryFakeList, updateShareAndView, updateShowStatus, queryCurrent } from './service';
import {
  queryDictList,
  hospitalList,
  hospitalDeptlist,
  diseaseList,
} from '@/services/ant-design-pro/api';
import type { BasicListItemDataType } from './data.d';
import styles from './style.less';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { Search } = Input;

const Info: FC<{
  title: React.ReactNode;
  value: React.ReactNode;
  bordered?: boolean;
}> = ({ title, value, bordered }) => (
  <div className={styles.headerInfo}>
    <span>{title}</span>
    <p>{value}</p>
    {bordered && <em />}
  </div>
);

export const BasicList: FC = () => {
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const [typeVisible, handleTypeVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<Object>({});
  const [list, setList] = useState<Array>([]);
  const [total, setTotal] = useState<number>(0);
  const [pageNum, setPageNum] = useState<number>(1);
  const [param, setParam] = useState<Object>({
    pageNum: 1,
    pageSize: 10,
    hospitalId: sessionStorage.getItem(`hosiptaAuthlId`),
  });
  console.log('sessionStorage.getItem(`hosiptaAuthlId`)', sessionStorage.getItem(`hosiptaAuthlId`));
  let currentUser = JSON.parse(sessionStorage.getItem('currentUser'));

  // const { data: currentUser, loading } = useRequest(() => {
  //   return queryCurrent();
  // });

  const initList = async (param: object) => {
    try {
      const response = await queryFakeList(param);
      if (response.code == 200) {
        console.log('respose', response);
        setList(response.data.records);
        setTotal(response.data.total);
      } else {
        message.error('获取数据失败!');
      }
    } catch (error) {
      message.error('获取数据失败' + error);
    }
  };

  const showItem = async (postData: object) => {
    const hide = message.loading('正在处理');
    try {
      const response = await updateShowStatus(postData);
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
        initList(param);
      } else {
        message.error('处理失败!');
      }
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  const ListContent = ({
    data: { publishTime, status, baseArticleId },
  }: {
      data: BasicListItemDataType;
    }) => (
      <div className={styles.listContent}>
        <div className={styles.listContentItem}>
          <p>{moment(publishTime).format('YYYY-MM-DD HH:mm')}</p>
          <Space>
            {currentUser ? (
              currentUser.adminType == 1 || currentUser.adminType == 0 ? (
                <a
                  key="update"
                  onClick={(e) => {
                    e.preventDefault();
                    history.push('/content/creation-edit-detail?id=' + baseArticleId);
                  }}
                >
                  编辑
              </a>
              ) : <a
                key="comment"
                onClick={(e) => {
                  e.preventDefault();
                  history.push('/content/doctor-creation-detail?id=' + baseArticleId);
                }}
              >
                  查看
          </a>
            ) : null}
            <a
              key="hide"
              onClick={(e) => {
                e.preventDefault();
                // showEditModal(item);
                let postData = {
                  baseArticleId: baseArticleId, //文章id
                  status: status == 0 ? 1 : 0, //状态 1 显示 0 不显示
                };

                showItem(postData);
              }}
            >
              {status == 1 ? '对外隐藏' : '对外显示'}
            </a>
            {/* {currentUser ? (
              currentUser.adminType == 1 || currentUser.adminType == 0 ? (
                <a
                  key="update"
                  onClick={(e) => {
                    e.preventDefault();
                    // showEditModal(item);
                    let currentRow = { baseArticleId: baseArticleId };
                    setCurrentRow(currentRow);
                    handleModalVisible(true);
                  }}
                >
                  更新数据
              </a>
              ) : null
            ) : null} */}
          </Space>
        </div>
      </div>
    );

  // const {
  //   data: listData,
  //   loading,
  //   mutate,
  // } = useRequest(() => {
  //   return queryFakeList({
  //     pageNum: 1,
  //     pageSize: 1000,
  //   });
  // });

  //console.log('data', listData);
  //const list = listData?.records || [];

  // const paginationProps = {
  //   showSizeChanger: true,
  //   showQuickJumper: true,
  //   pageSize: 10,
  //   total: listData?.total || 0,
  // };

  const IconText = ({ icon, text }: { icon: React.FC; text: string }) => (
    <Space>
      {React.createElement(icon)}
      {text}
    </Space>
  );

  const onChange = ({ target: { value } }: RadioChangeEvent) => {
    console.log('radio1 checked', value);
    let paramNew = {
      pageNum: 1,
      pageSize: 10,
      hospitalId: sessionStorage.getItem(`hosiptaAuthlId`),
    };
    if (value == 'all') {
    } else {
      paramNew.channel = value;
    }
    setParam(paramNew);
    initList(paramNew);
  };

  const onSearch = (value: string) => {
    param.articleTitle = value;
    param.pageNum = 1;
    setParam(param);
    initList(param);
  };

  const extraContent = (
    <div className={styles.extraContent}>
      {/* <RadioGroup defaultValue="all" onChange={onChange}>
        <RadioButton value="all">全部</RadioButton>
        <RadioButton value="130060">科普文章</RadioButton>
        <RadioButton value="130100">病例交流</RadioButton>
      </RadioGroup>
      <Search className={styles.extraContentSearch} placeholder="请输入" onSearch={onSearch} /> */}
      {currentUser ? (
        currentUser.adminType == 1 || currentUser.adminType == 0 ? <Button type="primary" onClick={(e) => {
          e.preventDefault();
          handleTypeVisible(true);
        }}> + 代医生发布</Button> : null) : null}

    </div>
  );

  const renderTitle = ({ item }) => (
    <div className={styles.titleContent}>
      <span>
        {item.deptName} | {item.doctorName}
      </span>
      <div>{item.articleTitle}</div>
      <div className={styles.contentRow}>
        <div className={styles.contentType}>{item.channelName}</div>
        <div className={styles.contentType}>{item.isSelfPublish == "0" ? "代发布" : "自发布"}</div>
      </div>
      <Space>
        <IconText icon={StarOutlined} text={item.viewNum} key="list-vertical-star-o" />
        <IconText icon={LikeOutlined} text={item.likeNum} key="list-vertical-like-o" />
        <IconText icon={MessageOutlined} text={item.commentNum} key="list-vertical-message" />
      </Space>
    </div>
  );

  const handleShareAndView = async (record: API.RuleListItem[]) => {
    const hide = message.loading('正在处理');
    try {
      const response = await updateShareAndView(record);
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
      } else {
        message.error('处理失败!');
      }
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  useEffect(() => {
    initList(param);
  }, []);
  return (
    <div>
      <PageContainer>
        <ModalForm
          title="创作类型"
          width="300px"
          submitter={false}
          visible={typeVisible}
          onVisibleChange={handleTypeVisible}
        >
          <Space>
            <Button value="130060" onClick={(e) => {
              e.preventDefault();
              history.push('/content/science-detail?channel=130060');
            }}>疾病知识科普</Button>
            <Button value="130100" onClick={(e) => {
              e.preventDefault();
              history.push('/content/science-detail?channel=130100');
            }}>临床案例分享</Button>
          </Space>
        </ModalForm>
        {modalVisible ? (
          <ModalForm
            title={'更新数据'}
            width="500px"
            layout="horizontal"
            visible={modalVisible}
            onVisibleChange={handleModalVisible}
            onFinish={async (value) => {
              // value.viewNum = type;
              // value.likeNum = type;
              value.baseArticleId = currentRow.baseArticleId;
              console.log('value', value);
              let success = await handleShareAndView(value as Object);
              if (success) {
                handleModalVisible(false);
                // let param = {
                //   pageNum: pageNum,
                //   pageSize: 10,
                // };
                // param.pageNum=pageNum;
                initList(param);
              }
            }}
          >
            <ProFormDigit
              rules={[
                {
                  required: true,
                  message: '请输入',
                },
              ]}
              label="阅读量"
              width="md"
              min={1}
              name="viewNum"
            />
            <ProFormDigit
              rules={[
                {
                  required: true,
                  message: '请输入',
                },
              ]}
              label="点赞量"
              width="md"
              min={1}
              name="likeNum"
            />
          </ModalForm>
        ) : null}
        <Card>
          <div style={{ marginBottom: 20 }}>
            <RadioGroup defaultValue="all" onChange={onChange}>
              <RadioButton value="all">全部</RadioButton>
              <RadioButton value="130060">科普文章</RadioButton>
              <RadioButton value="130100">病例交流</RadioButton>
            </RadioGroup>
          </div>
          <QueryFilter defaultCollapsed split
            onFinish={async (value) => {
              console.log('value-----------', value);
              value.pageNum = 1;
              value.pageSize = 20;
              if (param.channel != "all") {
                value.channel = param.channel;
              }
              initList(value);
            }}>
            <ProFormText name="articleTitle" label="文章标题" />
            <ProFormSelect
              width="md"
              name="hospitalId"
              label="医院"
              showSearcha
              fieldProps={{
                labelCol: { span: 8 },
                wrapperCol: { span: 14 },
              }}
              request={async ({ keyWords }) => {
                let query = {
                  likeQuery: {
                    name: keyWords,
                  },
                  pageNum: 1,
                  pageSize: 20,
                };
                return hospitalList(query).then(({ data }) => {
                  return data.list.map((item) => {
                    return {
                      label: item.name,
                      value: item.id,
                    };
                  });
                });
              }}
            />
            <ProFormDependency name={['hospitalId']}>
              {({ hospitalId }) => {
                return (
                  <ProFormSelect
                    width="150px"
                    // params={{
                    //   key: hospital ?.value,
                    // }}
                    name="deptId"
                    label="科室"
                    showSearch
                    // fieldProps={{
                    //   labelInValue: true,
                    // }}
                    request={async () => {
                      console.log('hospital', hospitalId);
                      let query = {
                        eqQuery: {
                          hospitalId: hospitalId,
                          level: 1,
                        },
                        pageNum: 1,
                        pageSize: 20,
                      };

                      // let arr = user.split('-');
                      return hospitalDeptlist(query).then(({ data }) => {
                        return data.list.map((item) => {
                          return {
                            label: item.name,
                            value: item.id,
                          };
                        });
                      });
                    }}
                  />
                );
              }}
            </ProFormDependency>
            <ProFormSelect
              width="md"
              name="status"
              label="显示状态"
              options={[
                {
                  value: 0,
                  label: '隐藏',
                },
                {
                  value: 1,
                  label: '显示',
                },
              ]}
            />
          </QueryFilter>

        </Card>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title=""
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
            extra={extraContent}
          >
            <List
              // itemLayout="vertical"
              size="large"
              rowKey="id"
              // loading={loading}
              // pagination={paginationProps}
              pagination={{
                onChange: (page) => {
                  console.log(page);
                  setPageNum(page);
                  param.pageNum = page;
                  setParam(param);
                  initList(param);
                },
                showSizeChanger: true,
                showQuickJumper: true,
                pageSize: 10,
                total: total,
              }}
              dataSource={list}
              renderItem={(item) => (
                <List.Item
                // actions={[

                // ]}
                >
                  <List.Item.Meta
                    avatar={
                      <Avatar
                        src={'http://oss.yizuoyiyou.com.cn' + item.doctorHeadPic}
                        shape="square"
                        size="large"
                      />
                    }
                    title={renderTitle({ item })}
                  // description={renderDescription({ item })}
                  />
                  <ListContent data={item} />
                </List.Item>
              )}
            />
          </Card>
        </div>
      </PageContainer>
    </div>
  );
};

export default BasicList;
